#include<iostream>
#include<stdlib.h>
#include<stdio.h>

using namespace std;

typedef struct _node
{
	int data;
	struct _node *next;
}node;

node *list_init()
{
	node *list = NULL;

	list = (node *)malloc(sizeof(node));
	if(list == NULL)
		return list;

	list->next = NULL;
	
	return list;
}

node *list_create()
{
	node *head, *p, *s;
	int x, cycle=1;

	head = (node *)malloc(sizeof(node));
	p = head;
	while(cycle)
	{
		cout << "please input the number:";
		scanf("%d", &x);
		if(x != 0)
		{
			s=(node *)malloc(sizeof(node));
			s->data=x;
			cout << "s->data=" << s->data << endl;
			p->next=s;
			p = s;
		}
		else
		{
			cycle = 0;
		}
	}

	head = head->next;
	p->next = NULL;

	return head;
}

int list_length(node *head)
{
	int len = 0;

	while(head)
	{
		head = head->next;
		len++;
	}

	return len;
}

void list_print(node *head)
{
	while(head)
	{
		cout << head->data << " ";
		head = head->next;
	}
	cout << endl;
}

int list_insert(node *head, int idx, int data)
{
	node *pre = head;
	node *cur = head;
	int i = 1;

	while(pre!=NULL)
	{
		i++;
		pre = pre->next;
		if(i==idx-1)
			break;
	}

	if(i!=idx-1)
		return 0;

	cur = (node *)malloc(sizeof(node));
	cur->data = data;
	cur->next = prev->next;
	prev->next = cur;

	return 1;
}

node * list_delete(node *head, int data)
{
	node *pre = NULL;
	node *cur = head;

	while(cur!=NULL)
	{
		if(cur->data == data)
			break;

		pre = cur;
		cur=cur->next;
	}

	prev->next = cur->next;
	free(cur);

	return head;
}

node * list_reverse(node *head)
{
	node *prev = NULL;
	node *cur = head;
	node *next = NULL;
	node *rhead = NULL;

	while(cur != NULL)
	{
		next = cur->next;
		if(next == NULL)
			rhead = cur;

		cur->next = prev;
		
		prev = cur;
		cur = next;
	}

	return rhead;
}

int main()
{
	node *list = NULL;
	node *rlist = NULL;

	list = list_create();
	cout << "list len = " << list_length(list) << endl;
	list_print(list);
	rlist = list_reverse(list);
	list_print(rlist);

	return 0;
}
